#!/usr/bin/env python

"""
Network Monitoring System Server Mock

"""

import json, socket

hash_number = 1;

def register(params):
	answer = { 'command':'register' }
	global hash_number
	services=''
	client_hash = params['hash']
	client_port = params['port']
	client_service_list = params['service_list']
	if client_hash == '':
		answer['status'] = 1 # 1 - means ok
		answer['hash'] = hash_number
		hash_number += 1
	elif client_hash == -1:
		answer['status'] = 2 # 2 - force new hash
		answer['hash'] = ''
	else:
		answer['status'] = 0 # 0 - means hash reuse
		answer['hash'] = client_hash
	for i in client_service_list:
		services = services + i
	print (str(client_hash) + ';' + str(client_port) + ';' + services)
	
	return answer;

# End of function

def unsupported():
	return { 'command' : 'unknown', 'status' : -1 }
	
	
# End of funciton
options = {}
options['host'] = ''
options['port'] = 5000

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((options['host'],options['port']))

server.listen(5)
print 'Network Monitoring Simple Server started'

while 1:
	client, address = server.accept()
	clientData = client.recv(1024)
	question = json.loads(clientData)
	if question['command'] == 'register':
		response = register(question['params'])
	else:
		print "Unsupported command"
		response = unsupported()
	response = json.dumps(response) 
	client.send(response)
	exit(0)
	
	
